package com.xzy.java.ccc;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * 泛型数组、集合
 *
 * @author xzy.xiao
 * @date 2023/3/8  15:35
 */
@Slf4j
public class CccTest<T> {
    T[] array1;
    List<T>[] array2;
    T[][][] array3;

    public static void main(String[] args) throws NoSuchFieldException {
        Field field = CccTest.class.getDeclaredField("array1");
        Type genericType = field.getGenericType();

        /*
         * GenericArrayType：泛型数组，例如T[]
         */
        if (genericType instanceof GenericArrayType) {
            GenericArrayType genericArrayType = (GenericArrayType) genericType;

            /*
             * 获取数组元素的类型信息：
             *     T[] => T                是 TypeVariable
             *     List<T>[] => List<T>    是 GenericArrayType
             *     T[][][] => T[]][]       是 GenericArrayType
             */
            Type genericComponentType = genericArrayType.getGenericComponentType();
            log.info(String.valueOf(genericComponentType));
            log.info(genericArrayType.getClass().toString());
        }
    }
}
